package com.agileboot.admin.customize.config;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.agileboot.admin.controller.system.MonitorController;
import com.agileboot.domain.common.dto.CurrentLoginUserDTO;
import com.agileboot.domain.system.user.UserApplicationService;
import com.agileboot.infrastructure.user.AuthenticationUtils;
import com.agileboot.infrastructure.user.web.SystemLoginUser;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class CustomRequestFilter extends OncePerRequestFilter {
    /**
     * 在yml文件中设置了前缀 context-path: /admin/  。而request.getServletPath()获取是没有包括/admin的。所以不用写/admin 这个
     */
    private static final Set<String> EXCLUDE_URLS = new HashSet<>(Set.of("/login", "/register", "/getConfig", "/captchaImage", "/app/**", "/favicon.ico",
            "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/resourceFile/**"));
    private final AntPathMatcher pathMatcher = new AntPathMatcher();
    private final UserApplicationService userApplicationService;

    private MonitorController monitorController;

    public CustomRequestFilter(UserApplicationService userApplicationService, MonitorController monitorController) {
        this.userApplicationService = userApplicationService;
        this.monitorController = monitorController;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain filterChain) throws ServletException, IOException {
        String path = request.getServletPath();
//        System.out.println(path);
        // 跳过特定路径
        for (String excludeUrl : EXCLUDE_URLS) {
            if (pathMatcher.match(excludeUrl, path)) {
                filterChain.doFilter(request, response);
                System.out.println(path);
                return;
            }
        }
        // 在这里添加你的拦截逻辑
        // 例如，日志记录、验证特定请求头、验证自定义token等
        System.out.println("例如，日志记录、验证特定请求头、验证自定义token等");
        SystemLoginUser loginUser = AuthenticationUtils.getSystemLoginUser();
        if (loginUser != null) {
            CurrentLoginUserDTO currentUserDTO = userApplicationService.getLoginUserInfo(loginUser);
//            System.out.println(currentUserDTO.getUserInfo().getStatus());
            if (currentUserDTO.getUserInfo().getStatus() != 1) {
                // 返回自定义响应
//                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // 设置HTTP状态码为500
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                String jsonResponse = String.format("{\"code\":10502, \"msg\":\"登录失败：对不起， 您的账号：%s 已停用或冻结\"}", currentUserDTO.getUserInfo().getUsername());
                response.getWriter().write(jsonResponse);
                return;
            }
        }
        // 打印请求的URL
        System.out.println("Intercepted URL: " + request.getRequestURL().toString());
        System.out.println("例如，日志记录、验证特定请求头、验证自定义token等");

        // 继续过滤链
        filterChain.doFilter(request, response);
    }

    // 示例方法：从请求中获取token
    private String getTokenFromRequest(HttpServletRequest request) {
        // 通常token存储在请求头的Authorization字段中
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7); // 去掉 "Bearer " 前缀
        }
        return null; // 如果token不存在或格式不正确
    }
}

